#!/usr/bin/python2
# -*- coding: UTF-8 -*-
# 文件名：client.py

# from time import ctime
import threading
# import re     # 正则表达式模块
import socket               # 导入 socket 模块

host = socket.gethostname()  # 获取本地主机名
port = 12345                # 设置端口
BufferSize = 1024               # 获取到的最大字节数
Address = (host, port)
threads = []


def Send(sock):    # 发送消息
    while True:
        data = raw_input('输入你要发送的信息：>')
        sock.send(data)
        if data == 'quit':
            break


def Recv(sock):     #接收消息
    while True:
        data = sock.recv(BufferSize)
        if data == 'quit':
            sock.close()     # 退出时关闭socket
            break
        print data


tcpCliSock = socket.socket()
tcpCliSock.connect(Address)
print 'Please input your username:',
username = raw_input()
tcpCliSock.send(username)
data = tcpCliSock.recv(BufferSize)
if data == 'Reuse':
    print 'The username has been used!'
else:
    print data
    chat = threading.Thread(target=Send, args=(tcpCliSock,))    #创建发送信息线程
    threads.append(chat)
    chat = threading.Thread(target=Recv, args=(tcpCliSock,))    #创建接收信息线程
    threads.append(chat)
    for i in range(len(threads)):    #启动线程
        threads[i].start()
    threads[0].join()    # 在我们的设计中，send线程必然先于recv线程结束，所以此处只需要调用send的join，等待recv线程的结束。